<template>
  <!-- uni.getMenuButtonBoundingClientRect可获取小程序右上角操作胶囊按钮的元素信息 -->
  <view class="peripheral-container">
    <up-toast ref="uToastRef" />
    <map
      enable-3D
      :style="fullMapStyle"
      :latitude="latitude"
      :longitude="longitude"
      :markers="markers"
      :polyline="polyline"
      :include-points="includePoints">
      <cover-view v-show="!isOpenLocation" class="error-tip" @click="handleReLocation">您未开启定位，开启后点击此刷新</cover-view>
    </map>
    <view class="tabbar">
      <up-tabs
        :list="tab.optionList"
        :current="tab.currIndex"
        @change="handleTabChange"
        lineWidth="30"
        lineColor="`linear-gradient(to right, #0558a8, #1e7eba, #0558a8)`"
        :activeStyle="{ color: '#333333', fontWeight: 'bold', fontSize: '15px', transform: 'scale(1.05)' }"
        :inactiveStyle="{ color: '#606266', transform: 'scale(1)' }" />
    </view>
    <!-- 		adcode: 500112
		address: "龙湖冠寓(礼嘉天街店)"
		category: "汽车:加油站:充电站"
		city: "重庆市"
		distance: 941.34
		district: "渝北区"
		id: "606092139140119648"
		latitude: 29.674873
		longitude: 106.488413
		province: "重庆市"
		tel: "4006889501"
		title: "充小兽礼嘉龙塘湖超充站" -->
    <ycy-popup-draggable ref="popupDraggableRef" minHeight="320" draggableRange="600">
      <view class="poit-item" v-for="item in searchDataList" :key="item.id" @click.stop="handleOpenDetail(item)">
        <image class="poit-item-image" :src="item.imageUrl" />
        <view class="poit-item-content">
          <view class="poit-item-content-title">{{ item.title }}</view>
          <view class="poit-item-content-desc">
            {{ item.address && item.address.length > 15 ? `${item.address.substring(0, 13)}...` : item.address }}
          </view>
          <view class="poit-item-content-desc">
            {{ item.distance >= 1000 ? `${(item.distance / 1000).toFixed(2)}千米` : `${item.distance}米` }}
          </view>
        </view>
        <view class="poit-item-btn">
          <view class="poit-item-btn-item" @click.stop="handlePhoneCall(item)">
            <up-icon name="phone" size="18" color="#fff"></up-icon>
          </view>
          <view class="poit-item-btn-item" @click.stop="handleDetail(item)">
            <up-icon name="map" size="18" color="#fff"></up-icon>
          </view>
        </view>
      </view>
    </ycy-popup-draggable>
  </view>
</template>

<script setup>
  import { onLoad } from '@dcloudio/uni-app';
  import { computed, ref, onMounted,  reactive } from 'vue';
  import useMapUtils from '@/utils/map.js';

  const { getFullScreenMapStyleSync, getUserLocationMarker, getSearchLocation, MapMarker, defaultLoaction, openLocation } = useMapUtils();
  onMounted(() => {
    if (props.params.tabIndex) tab.currIndex = props.params.tabIndex;
    if (props.params.carId) currentCarId.value = props.params.carId;
    isOpenLocation.value = false;
    showMarker(tab.optionList[tab.currIndex].name);
  });

  // onLoad(options => {
  //   if (options.currentIndex) tab.currIndex = options.currIndex;
  //   if (options.currentCarId) currentCarId.value = options.currentCarId;
  // })

  const props = defineProps({
    params: {
      type: Object,
      default: () => ({
        currentCarId: '',
        currentIndex: 0
      })
    }
  });

  const uToastRef = ref();
  const popupDraggableRef = ref();
  const isOpenLocation = ref(false);
  const latitude = ref(defaultLoaction.latitude);
  const longitude = ref(defaultLoaction.longitude);
  const fullMapStyle = computed(() => getFullScreenMapStyleSync());
  const userMarker = computed(() => new MapMarker({ latitude: latitude.value, longitude: longitude.value }));
  const currentCarId = ref();
  const markers = ref([userMarker]);
  const polyline = ref([]);
  const includePoints = ref([]);
  const searchDataList = ref([]);
  const tab = reactive({
    optionList: [
      { name: '车辆年检', iconPath: '/static/image/location_car.png' },
      { name: '加油站', iconPath: '/static/image/location_gasStation.png' },
      { name: '充电站', iconPath: '/static/image/location_chargeStation.png' },
      { name: '维修保养', iconPath: '/static/image/location_repair.png' },
      { name: '停车场', iconPath: '/static/image/location_park.png' }
    ],
    currIndex: 0 //'加油站', '充电站', '维修保养', '停车场'
  });

  const showMarker = keyword => {
    getApp().globalData.toast.loading(uToastRef.value);
    // uni.showLoading({ title: '加载中' });
    getUserLocationMarker(
      (res, loaction) => {
        markers.value = [res];
        latitude.value = loaction.latitude;
        longitude.value = loaction.longitude;
        getCurrentTabMapPonits(keyword);
        isOpenLocation.value = true;
        // uni.hideLoading();
        getApp().globalData.toast.closeLoading(uToastRef.value);
      },
      () => {
        getCurrentTabMapPonits(keyword); //模拟
        // uni.hideLoading();
        getApp().globalData.toast.closeLoading(uToastRef.value);
        isOpenLocation.value = false;
        getApp().globalData.toast.error(uToastRef.value, '请打开手机定位');
      }
    );
  };

  const handleTabChange = async ({ index }) => {
    tab.currIndex = index;
    await popupDraggableRef.value.close();
    // if (!isOpenLocation.value) return;  //模拟
    getCurrentTabMapPonits(tab.optionList[index].name);
  };

  const handlePhoneCall = item => {
    if (!item.tel) {
      getApp().globalData.toast.error(uToastRef.value, '该门店暂无联系方式');
      return;
    }
    uni.makePhoneCall({
      phoneNumber: item.tel
    });
  };

  const handleOpenDetail = item => {
    if (tab.currIndex !== 0) return;
    uni.navigateTo({
      url: `/pages/peripheral/pages/locationDetail/locationDetail?carId=${currentCarId.value}`,
      success: res => {
        res.eventChannel.emit('locationItem', item);
      }
    });
  };

  const handleDetail = item => {
    openLocation({
      name: item.title,
      address: item.address,
      latitude: item.latitude,
      longitude: item.longitude
    });
    // getApp().globalData.toast.success(uToastRef.value, '详情页(敬请期待)');
  };

  const handleReLocation = () => {
    showMarker(tab.optionList[tab.currIndex].name);
  };

  const getCurrentTabMapPonits = keyword => {
    getSearchLocation(
      {
        keyword,
        latitude: latitude.value,
        longitude: longitude.value
      },
      ({ dataList }) => {
        const tempIncludePoints = [];
        const tempMarkers = [];
        dataList.forEach(item => {
          tempIncludePoints.push({ latitude: item.latitude, longitude: item.longitude });
          tempMarkers.push(
            new MapMarker({
              id: Number(item.id.substring(Math.floor(Math.random() * (item.id.length - 12 + 1)), 12)), //从它的字符串id中截取12位
              title: item.title,
              latitude: item.latitude,
              longitude: item.longitude,
              iconPath: tab.optionList[tab.currIndex].iconPath
            })
          );
        });
        tempMarkers.push(userMarker.value);

        includePoints.value = tempIncludePoints;
        markers.value = tempMarkers;

        // searchDataList.value = dataList;
        searchDataList.value = searchDataList.value = handleCustomFieldData(dataList);
        popupDraggableRef.value.open();

        // console.log('includePoints', includePoints.value);
        // console.log('markers', markers.value);
        // console.log('searchDataList', searchDataList.value);
      }
    );
  };

  const stationImgMap = {
    0: [
      'https://store.is.autonavi.com/showpic/7dcc077f200e8cf21eb02deb247fb565',
      'https://store.is.autonavi.com/showpic/bdfc2a89408bda18a401c6fb46e71a32',
      'https://store.is.autonavi.com/showpic/2576b3e24539c334e18dd282e42d6c29'
    ],
    1: [
      'https://store.is.autonavi.com/showpic/c091da63f388eef14b62db293a24f205',
      'https://store.is.autonavi.com/showpic/287428ee1745d89a8900db757774f085',
      'https://store.is.autonavi.com/showpic/bbb9d4e85575830ffcbfd1bb48d324ab'
    ],
    2: [
      'https://store.is.autonavi.com/showpic/aeaf07abb6711511e7d195769adef421',
      'https://store.is.autonavi.com/showpic/41be8b409ec0444d54347794fc7fab9b',
      'https://store.is.autonavi.com/showpic/2457129cb17fa046b32e5db63dbfef65'
    ],
    3: [
      'https://store.is.autonavi.com/showpic/ef051d381ffce2785bd952d17edd4325',
      'https://store.is.autonavi.com/showpic/f14951ca1ba0b8d141a574dc23a654da',
      'https://store.is.autonavi.com/showpic/ef051d381ffce2785bd952d17edd4325'
    ],
    4: [
      'https://store.is.autonavi.com/showpic/01ede7a5cb1af4bab326eab567a81ad0',
      'https://store.is.autonavi.com/showpic/2e3701110ae93bc137a78cdc0f25e717',
      'https://store.is.autonavi.com/showpic/7a27b205284053bf6f807b1bc64b0c25'
    ]
  };
  const handleCustomFieldData = dataList => {
    return dataList.map((item, index) => {
      return {
        ...item,
        imageUrl: stationImgMap[tab.currIndex][index % stationImgMap[tab.currIndex].length],
				imageUrlList: [
				  'https://store.is.autonavi.com/showpic/7dcc077f200e8cf21eb02deb247fb565',
				  'https://store.is.autonavi.com/showpic/bdfc2a89408bda18a401c6fb46e71a32',
				  'https://store.is.autonavi.com/showpic/2576b3e24539c334e18dd282e42d6c29'
				],
				price: Math.floor(Math.random() * 300 + 200),
				rate: 4,
				workTime: '周一到周五 8:00-18:00 周六周日 8:00-12:00',
				description: '本店提供车辆检测、维修、保养、保险等服务，方便快捷服务好! ',
				commentList: []
      };
    });
  };
</script>

<style lang="scss">
  .peripheral-container {
    position: relative;
    height: 100vh;
    .tabbar {
      position: absolute;
      top: 10%;
      left: 0;
      width: 100%;
      // border: 2px solid;
    }
  }
  .error-tip {
    position: absolute;
    top: 6%;
    left: 12px;
    padding: 6px 8px;
    font-size: 14px;
    border-radius: 14px;
    color: white;
    background-color: $uni-color-error;
  }

  .poit-item {
    position: relative;
    display: flex;
    color: $uni-text-color;
    padding: 16px 12px;
    border-bottom: 1px solid #efefef;

    &-image {
      @include size(80px, 80px);
      border-radius: 8px;
    }

    &-content {
      flex: 1;
      margin-left: 12px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      &-title {
        font-size: 15px;
        font-weight: bold;
      }

      &-desc {
        font-size: 12px;
        @include text-overflow;
      }
    }

    &-btn {
      position: absolute;
      right: 16px;
      bottom: 12px;
      // transform: translateX(-50%);
      display: flex;

      &-item {
        @include size(36px);
        @include flex-row(center, center);
        border-radius: 50%;
        background: linear-gradient(to right, #1e7eba, #0558a8);
      }

      &-item:last-of-type {
        margin-left: 12px;
      }
    }
  }
</style>
